package top.hekun.study.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Author: Sakura
 * @Date: 2021/4/10
 */
@RestController
@RequestMapping
public class WebFluxTestController {
    SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss:SSS");
    Logger logger = LoggerFactory.getLogger(WebFluxTestController.class);

    @GetMapping("/1")
    public Mono<String> getString1() {
        logger.info("进入方法1");
        Mono<String> stringMono = Mono.fromSupplier(() -> getMyString());
        logger.info("离开方法1");
        return stringMono;
    }

    @GetMapping("/2")
    public String getString2() {
        logger.info("进入方法1");
        String string = getMyString();
        logger.info("离开方法2");
        return string;
    }

    @GetMapping(value = "/3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getString3() {
        logger.info("进入方法3");
        Flux<String> flux = Flux.fromStream(IntStream.range(1, 10).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            StringBuffer buffer = new StringBuffer();
            buffer.append("flux >>");
            buffer.append(i);
            buffer.append(" >> 前的的时间: ");
            buffer.append(ft.format(new Date()));
            return buffer.toString();
        }));
        logger.info("离开方法3");
        return flux;
    }

    private String getMyString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("等待前的的时间: ");
        buffer.append(ft.format(new Date()));
        buffer.append("\r\n");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        buffer.append("等待后的的时间: ");
        buffer.append(ft.format(new Date()));
        return buffer.toString();
    }

}
